// 这是添加
import React, { useState, useEffect } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Modal, Input, Select, Switch, message, Upload, Form, InputNumber, Button, Space } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
const { TextArea } = Input;
import '../css/AddClassify.less'
import { addgoods } from '../../../../api/ycl'
import { log } from 'console';
import {api} from '../../../../api/ycl'
import {goodsImg} from '../../../../api/ycl'

interface PropsType {
    isModalOpen: boolean,
    closeModal(): void,
    coss(): void,
    dataApi(): void,
    data: any
}

export default function Add(props: PropsType) {

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>(); //图片地址 分类图标
    const [messageApi, contextHolder] = message.useMessage();
    const [form] = Form.useForm();
    const [img,setImg] = useState<string>() //存进图片地址
    useEffect(() => {
        form.setFieldsValue({
            categoryParent: '一级',
        })
    }, [props])

    // 上传图片
    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
      };
    const handleChange = async (info:any)=>{
        console.log('%c ======>>>>>>>>', 'color:orange;', '选了图片', info)
        let { file } = info
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
        if (!isJpgOrPng) {
            return message.error('你应该上传图片类型');
        }
        //判断文件大小  是否小于2M
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            return message.error('图片太大了，请上传小于2M 的文件');
            //让图片显示出来
        }
        let myFormData = new FormData()
        myFormData.append('file',info.file)
        // 发起请求
        try{
            let res = await goodsImg(myFormData)
            if(res.code == '200'){
                console.log(res.data);
                console.log(res.data.slice(3));
                setImg(res.data.slice(3))
            }
        }catch(err){
            console.log(err);
            
        }
        //让图片显示出来
        getBase64(info.file, (url) => {
            setImageUrl(url)
        });
    }
      
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    const layout = {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
    };

   

    // 点击确定按钮发起请求
    const onFinish = async (values: any) => { //点击确定
        props.closeModal()
        console.log(values);
        for (let i = 0; i < props.data.length; i++) {
            if (props.data[i].categoryName == values.categoryName) {
                messageApi.open({
                    type: 'error',
                    content: '已经有这个商品分类了',
                });
                return
            }

        }
        // 发起请求添加数据
        let data = ({
            categoryName: values.categoryName,
            categoryParent: values.categoryParent == '一级' ? 0 : 1,
            categorySort: values.categorySort,
            categoryStatus: values.categoryStatus === true ? '1' : '4',
            description: values.description,
            categoryImg:img
        })
        try {
            let res = await addgoods(data)
            if (res.code == '200') {
                props.dataApi()
                messageApi.open({
                    type: 'success',
                    content: '添加成功',
                });
            } else {
                console.log('失败');
            }
        } catch (err) {
            console.log(err);

        }
    };





    const cancel = () => {
        props.coss()
    }
    const handleCancel = () => {
        props.coss()
    }
    return (
        <div>
            {contextHolder}
            <Modal title="添加" open={props.isModalOpen} centered={true} footer={null} onCancel={handleCancel}>
                <Form
                    form={form}
                    {...layout}
                    name="nest-messages"
                    onFinish={onFinish}
                    style={{ maxWidth: 600 }}
                >
                    <Form.Item name='categoryName' label="分类名称" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name='categoryParent' label='上级分类'>
                        <Select
                            style={{ width: 120 }}
                            allowClear
                            defaultValue={['一级', '一级']}
                            disabled={true}
                            options={[
                                {
                                    value: '一级',
                                    label: '一级'
                                }
                            ]}
                        />
                    </Form.Item>
                    <Form.Item name='categorySort' label="排序" >
                        <InputNumber min={1} max={100000} defaultValue={1} />
                    </Form.Item>
                    <Form.Item name='categoryStatus' label='是否上架'>
                        <Switch />
                    </Form.Item>
                    <Form.Item name='picture' label='分类图标'   valuePropName="fileList"  /* 子节点的值的属性 */
                        getValueFromEvent={e => { /* 设置如何将 event 的值转换成字段值 */
                            if (Array.isArray(e)) {
                                return e
                            }
                            return e && e.fileList
                        }}>
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            beforeUpload={()=>false}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item name='description' label="分类描述">
                        <Input.TextArea />
                    </Form.Item>
                    <div className='button'>
                        <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
                            <Button type="primary" onClick={cancel}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit" className='button-subnit'>
                                确定
                            </Button>
                        </Form.Item>
                    </div>
                </Form>
            </Modal>
        </div>
    )
}